#include "modifynamethread.h"

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcfilefo.h"
#include "dcmtk/dcmdata/dcdatset.h"
#include "dcmtk/dcmdata/dcdeftag.h"

#include <QDir>

ModifyNameThread::ModifyNameThread(const QStringList &files, const QString &srcDir, const QString &destDir, QObject *parent):
    m_files(files),
    m_destDir(destDir),
    m_srcDir(srcDir),
    QThread(parent)
{

}

void ModifyNameThread::run()
{
    foreach (const QString &f, m_files) {
        OFCondition cond;
        DcmFileFormat dff;
        cond = dff.loadFile(f.toLocal8Bit().data());
        if (cond.bad()) {
            emit resultReady(false, f+": "+QString(cond.text()));
        } else {
            DcmDataset *dset = dff.getDataset();
            cond = dset->putAndInsertString(DCM_PatientName, "XXX");
            cond = dset->putAndInsertString(DCM_InstitutionName, "XXXXXX");
            QString dest = f;
            dest.replace(m_srcDir, m_destDir, Qt::CaseInsensitive);
            QDir().mkpath(dest.left(dest.lastIndexOf("/")));
            cond = dset->saveFile(dest.toLocal8Bit().data(), dset->getOriginalXfer());
            if (cond.bad()) {
                emit resultReady(false, dest+": "+QString(cond.text()));
            } else {
                emit resultReady(true, dest);
            }
        }
    }
}
